/**
 * 店铺种子数据脚本
 * 用于创建测试店铺数据
 */

const mongoose = require('mongoose');
const Shop = require('../src/models/shop.model');
const User = require('../src/models/user.model');
const Product = require('../src/models/product.model');
require('dotenv').config();

// 连接数据库
const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/jd-mall');
    console.log('✅ 数据库连接成功');
  } catch (error) {
    console.error('❌ 数据库连接失败:', error);
    process.exit(1);
  }
};

// 店铺种子数据
const seedShops = [
  {
    name: 'Apple官方旗舰店',
    description: 'Apple官方授权旗舰店，正品保证，全国联保',
    logo: 'https://picsum.photos/200/200?random=101',
    banner: 'https://picsum.photos/800/300?random=201',
    type: 'official',
    categories: ['手机数码', '电脑办公'],
    rating: {
      overall: 4.9,
      service: 4.9,
      logistics: 4.8,
      description: 4.9
    },
    announcement: '新品iPhone 15系列现货发售，享受官方保修服务',
    tags: ['官方正品', '全国联保', '快速发货'],
    certification: {
      isVerified: true,
      verifiedAt: new Date(),
      businessLicense: 'BL001'
    },
    shipping: {
      freeShippingThreshold: 0,
      shippingFee: 0,
      supportedRegions: ['全国'],
      averageDeliveryTime: 1
    },
    afterSales: {
      returnPolicy: '15天无理由退货',
      warrantyPeriod: 365,
      supportRefund: true,
      supportExchange: true
    },
    stats: {
      totalProducts: 50,
      totalSales: 10000,
      totalOrders: 5000,
      monthlyRevenue: 500000,
      followers: 50000
    }
  },
  {
    name: '小米官方旗舰店',
    description: '小米科技官方旗舰店，米粉专属购物天堂',
    logo: 'https://picsum.photos/200/200?random=102',
    banner: 'https://picsum.photos/800/300?random=202',
    type: 'official',
    categories: ['手机数码', '智能家居'],
    rating: {
      overall: 4.8,
      service: 4.8,
      logistics: 4.7,
      description: 4.8
    },
    announcement: '小米14系列新品上市，性价比之王',
    tags: ['性价比', '科技潮品', '快速发货'],
    certification: {
      isVerified: true,
      verifiedAt: new Date(),
      businessLicense: 'BL002'
    },
    shipping: {
      freeShippingThreshold: 99,
      shippingFee: 10,
      supportedRegions: ['全国'],
      averageDeliveryTime: 2
    },
    afterSales: {
      returnPolicy: '7天无理由退货',
      warrantyPeriod: 365,
      supportRefund: true,
      supportExchange: true
    },
    stats: {
      totalProducts: 80,
      totalSales: 15000,
      totalOrders: 8000,
      monthlyRevenue: 300000,
      followers: 80000
    }
  },
  {
    name: '华为官方旗舰店',
    description: '华为技术有限公司官方旗舰店',
    logo: 'https://picsum.photos/200/200?random=103',
    banner: 'https://picsum.photos/800/300?random=203',
    type: 'official',
    categories: ['手机数码', '电脑办公'],
    rating: {
      overall: 4.7,
      service: 4.7,
      logistics: 4.6,
      description: 4.7
    },
    announcement: 'Mate系列新品发布，科技美学新高度',
    tags: ['科技创新', '品质保证', '官方正品'],
    certification: {
      isVerified: true,
      verifiedAt: new Date(),
      businessLicense: 'BL003'
    },
    shipping: {
      freeShippingThreshold: 199,
      shippingFee: 15,
      supportedRegions: ['全国'],
      averageDeliveryTime: 2
    },
    afterSales: {
      returnPolicy: '7天无理由退货',
      warrantyPeriod: 365,
      supportRefund: true,
      supportExchange: true
    },
    stats: {
      totalProducts: 60,
      totalSales: 8000,
      totalOrders: 4000,
      monthlyRevenue: 400000,
      followers: 60000
    }
  },
  {
    name: '京东数码专营店',
    description: '专业数码产品销售，品质保证，服务至上',
    logo: 'https://picsum.photos/200/200?random=104',
    banner: 'https://picsum.photos/800/300?random=204',
    type: 'authorized',
    categories: ['手机数码', '摄影摄像'],
    rating: {
      overall: 4.6,
      service: 4.6,
      logistics: 4.5,
      description: 4.6
    },
    announcement: '数码新品大促销，限时优惠不容错过',
    tags: ['品质保证', '价格优惠', '服务专业'],
    certification: {
      isVerified: true,
      verifiedAt: new Date(),
      businessLicense: 'BL004'
    },
    shipping: {
      freeShippingThreshold: 299,
      shippingFee: 20,
      supportedRegions: ['全国'],
      averageDeliveryTime: 3
    },
    afterSales: {
      returnPolicy: '7天无理由退货',
      warrantyPeriod: 180,
      supportRefund: true,
      supportExchange: true
    },
    stats: {
      totalProducts: 200,
      totalSales: 12000,
      totalOrders: 6000,
      monthlyRevenue: 200000,
      followers: 30000
    }
  },
  {
    name: '潮流服饰旗舰店',
    description: '时尚潮流服饰，引领穿搭新风尚',
    logo: 'https://picsum.photos/200/200?random=105',
    banner: 'https://picsum.photos/800/300?random=205',
    type: 'flagship',
    categories: ['服装鞋帽', '箱包配饰'],
    rating: {
      overall: 4.5,
      service: 4.5,
      logistics: 4.4,
      description: 4.5
    },
    announcement: '春季新品上市，时尚潮流不容错过',
    tags: ['时尚潮流', '品质面料', '快速发货'],
    certification: {
      isVerified: false
    },
    shipping: {
      freeShippingThreshold: 199,
      shippingFee: 15,
      supportedRegions: ['全国'],
      averageDeliveryTime: 3
    },
    afterSales: {
      returnPolicy: '7天无理由退货',
      warrantyPeriod: 90,
      supportRefund: true,
      supportExchange: true
    },
    stats: {
      totalProducts: 300,
      totalSales: 20000,
      totalOrders: 15000,
      monthlyRevenue: 150000,
      followers: 25000
    }
  }
];

// 创建店铺数据
const createShops = async () => {
  try {
    console.log('🌱 开始创建店铺数据...');

    // 清空现有店铺数据
    await Shop.deleteMany({});
    console.log('🗑️ 已清空现有店铺数据');

    // 获取或创建测试用户作为店主
    let testUsers = await User.find().limit(5);
    if (testUsers.length === 0) {
      console.log('⚠️ 没有找到用户数据，请先运行用户种子数据脚本');
      return;
    }

    // 为每个店铺分配店主
    const shopsWithOwners = seedShops.map((shop, index) => ({
      ...shop,
      owner: testUsers[index % testUsers.length]._id
    }));

    // 创建店铺
    const createdShops = await Shop.insertMany(shopsWithOwners);
    console.log(`✅ 成功创建 ${createdShops.length} 个店铺`);

    // 更新现有商品的店铺关联
    const products = await Product.find();
    if (products.length > 0) {
      console.log('🔄 正在更新商品的店铺关联...');
      
      for (let i = 0; i < products.length; i++) {
        const product = products[i];
        const shopIndex = i % createdShops.length;
        product.shop = createdShops[shopIndex]._id;
        await product.save();
      }
      
      console.log(`✅ 已更新 ${products.length} 个商品的店铺关联`);
    }

    console.log('🎉 店铺种子数据创建完成！');
    
    // 显示创建的店铺信息
    createdShops.forEach((shop, index) => {
      console.log(`${index + 1}. ${shop.name} (${shop.type})`);
    });

  } catch (error) {
    console.error('❌ 创建店铺数据失败:', error);
  }
};

// 主函数
const main = async () => {
  await connectDB();
  await createShops();
  await mongoose.connection.close();
  console.log('👋 数据库连接已关闭');
};

// 运行脚本
if (require.main === module) {
  main();
}

module.exports = { createShops };
